package eu.trojanbug.spring.security.gae;

import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.MutableGrantedAuthoritiesContainer;
import org.springframework.security.ui.AuthenticationDetailsSourceImpl;
import org.springframework.security.ui.preauth.PreAuthenticatedGrantedAuthoritiesAuthenticationDetails;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class GoogleAccountsAuthenticationDetailsSource extends
		AuthenticationDetailsSourceImpl {
	/**
	 * Public constructor which overrides the default AuthenticationDetails
	 * class to be used.
	 */
	public GoogleAccountsAuthenticationDetailsSource() {
		super
				.setClazz(PreAuthenticatedGrantedAuthoritiesAuthenticationDetails.class);
	}

	public Object buildDetails(Object context) {
		Object result = super.buildDetails(context);
		if (result instanceof MutableGrantedAuthoritiesContainer) {
			MutableGrantedAuthoritiesContainer mac = (MutableGrantedAuthoritiesContainer) result;
			UserService userService = UserServiceFactory.getUserService();
			if (userService.isUserAdmin()) {
				mac.setGrantedAuthorities(new GrantedAuthority[] {
						new GrantedAuthorityImpl("ROLE_GOOGLE_APP_ADMIN"),
						new GrantedAuthorityImpl("ROLE_GOOGLE_APP_USER"),
						new GrantedAuthorityImpl("GOOGLE_AUTH_DOMAIN_"+userService.getCurrentUser()
								.getAuthDomain()) });
			} else if (userService.isUserLoggedIn()) {
				mac.setGrantedAuthorities(new GrantedAuthority[] {
						new GrantedAuthorityImpl("ROLE_GOOGLE_APP_USER"),
						new GrantedAuthorityImpl("GOOGLE_AUTH_DOMAIN_"+userService.getCurrentUser()
								.getAuthDomain()) });
			}
		}
		return result;
	}

}
